package com.liu.project.filter;

import com.alibaba.fastjson.JSON;
import com.liu.project.pojo.LoginUser;
import com.liu.project.utils.JwtUtils;
import com.liu.project.utils.Message;
import com.liu.project.utils.RedisUtil;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * @program: project
 * @description: token过滤,是否合法
 * @author: 86187
 * @create: 2022-03-03 15:33
 **/

@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {



    private RedisUtil redisUtil;
    public  JwtAuthenticationFilter (RedisUtil redisUtil){
        this.redisUtil=redisUtil;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)  throws ServletException, IOException {

        String token = request.getParameter(JwtUtils.TOKEN_HEADER);
        if (StringUtils.isBlank(token)) {
            token = request.getHeader(JwtUtils.TOKEN_HEADER);
            System.out.println(token);
        }
        if (token!=null && StringUtils.startsWith(token,JwtUtils.TOKEN_PREFIX)) {
            token = StringUtils.substring(token, JwtUtils.TOKEN_PREFIX.length());
        }else {
            filterChain.doFilter(request,response);
            return;
        }
               try{
                    String username = JwtUtils.getUsername(token);
                    if (username!=null && SecurityContextHolder.getContext().getAuthentication() == null){

                        LoginUser loginUser=(LoginUser) redisUtil.get("user:"+username);

                      System.out.println("doFilterInternal===>"+loginUser);
                        if (JwtUtils.validateToken(token,loginUser)){
                            // 将用户信息存入 authentication，方便后续校验
                            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
                            authentication.setDetails(new WebAuthenticationDetails(request));
                            // 将 authentication 存入 ThreadLocal，方便后续获取用户信息
                            SecurityContextHolder.getContext().setAuthentication(authentication);
                        }
                    }

                }
                catch (Exception e){
                    response.setContentType("application/json;charset=UTF-8");
                    response.getWriter().write(JSON.toJSONString(new Message(400,"失败")));
                    return;
                }

        filterChain.doFilter(request, response);
        }

}
